from rest_framework import status
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from pet.ser import *
from pet.models import PetModel
from user.models import UserModel


class UserListView(APIView):
    def get(self, request):
        users = UserModel.objects.all()
        user_data = [{'id': user.id, 'name': user.nikename} for user in users]
        return Response({'code': 200, 'data': user_data})
class SpeciesListView(APIView):
    def get(self, request):
        species = SpeciesModel.objects.all()
        species_data = [{'id': sp.id, 'species': sp.species} for sp in species]
        return Response({'code': 200, 'data': species_data})
# 增删改
class AddPetView(APIView):
    def get(self, request, pk):
        try:
            # Use get() to retrieve a single instance by primary key
            pet = PetModel.objects.get(pk=pk)
            return Response({'code': 200, 'data': PetSerializer(pet).data})
        except PetModel.DoesNotExist:
            return Response({'code': 404, 'msg': '未找到该宠物'}, status=status.HTTP_404_NOT_FOUND)

    def post(self, request):
        ser = PetSerializer(data=request.data)
        if not ser.is_valid():
            return Response({'code': 200, 'msg': '参数不正确','err': ser.errors})
        ser.save()
        return Response({'code': 200, 'msg': '添加成功'})

    def put(self, request, pk):
        pet = PetModel.objects.get(pk=pk)
        ser = PetSerializer(pet, data=request.data)
        if not ser.is_valid():
            return Response({'code': 400, 'msg': '参数不正确'})
        ser.save()
        return Response({'code': 200, 'msg': '修改成功'})

    def delete(self, request, pk):
        try:
            pet = PetModel.objects.get(pk=pk)
        except PetModel.DoesNotExist:
            return Response({'code': 404, 'msg': '未找到该宠物'}, status=status.HTTP_404_NOT_FOUND)

        pet.delete()
        return Response({'code': 200, 'msg': '删除成功'})


class GetUserPetIdView(APIView):
    def get(self, request,id):
        user = get_object_or_404(UserModel, pk=id)
        pets = PetModel.objects.filter(user=user)
        if not pets.exists():
            return Response({'code': 404, 'mes':'宠物不存在'})
        pet_data = pets.values('id', 'name')  # 获取宠物的ID和名称
        return Response({'code': 200, 'pets': list(pet_data)})